//
//  EmptyView.swift
//  HinsLive
//
//  Created by haoxian on 2019/4/19.
//  Copyright © 2019 Hins. All rights reserved.
//

import UIKit
import RxSwift


class EmptyView: UIView {
    
    private struct Message {
        static var fetchingMsg = ""
        static var errorMsg = ""
    }
    
    private let messageLabel: UILabel = {
        let label = UILabel()
        label.textColor = .black
        label.font = .systemFont(ofSize: 17)
        label.textAlignment = .center
        label.text = Message.fetchingMsg
        return label
    }()
    
    private lazy var refetchTap = UITapGestureRecognizer(target: self, action: #selector(EmptyView.refetchDidTap))
    
    let didTapSubject = PublishSubject<EmptyView>()
    
    init(fetchingMsg: String = "", errorMsg: String = "网络开小差啦，点击重试...") {
        super.init(frame: .zero)
        Message.fetchingMsg = fetchingMsg
        Message.errorMsg = errorMsg
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

private extension EmptyView {
    func setupUI() {
         backgroundColor = .commonBackgroundColor
        addSubview(messageLabel)
        messageLabel.snp.makeConstraints { (make) in
            make.centerY.left.right.equalToSuperview()
            make.height.equalTo(50)
        }
    }
}

extension EmptyView {
    @objc func refetchDidTap() {
        didTapSubject.onNext(self)
    }
    
    func showErrorMessage(_ msg: String? = nil) {
        var message = Message.errorMsg
        if let msg = msg {
            message = msg
        }
        messageLabel.text = message
        addGestureRecognizer(refetchTap)
    }
    
    func showFetchingMessage() {
        removeGestureRecognizer(refetchTap)
        messageLabel.text = Message.fetchingMsg
    }
}
